package controller.UserController;

import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        // 1、校验
        // 校验登陆身份
        // 校验参数
        String phone_number = req.getParameter("phone_number");
        String password = req.getParameter("password");

        System.out.println(phone_number);
        System.out.println(password);

        if(StringUtil.isEmpty(phone_number)||StringUtil.isEmpty(password)){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"参数有误！"));
            resp.getWriter().write(respJson);
            return ;
        }
        // 2、登录
        int ret = userService.login(phone_number,password);
        if(ret==1){
            // 3、添加session信息
            User user = new User(phone_number,password);
            HttpSession session = req.getSession(true);

            user = userService.getUserByPhoneNumber(phone_number);
            session.setAttribute(AppVariable.SESSION_USERINFO_KEY,user);
            String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(200));
            resp.getWriter().write(respJson);
            return ;
        }else{
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"用户名或密码错误！请重新登陆"));
            resp.getWriter().write(respJson);
        }
    }
}
